import useEventListener from '@/hooks/event/useEventListener';

const useHistory = () => {
  const history = ref(window.history);
  const historyState = computed(() => history.value.state);
  const canBack = computed(() => !!historyState.value.back);
  const canForward = computed(() => !!historyState.value.forward);

  // pushState、replaceState两个api是不会被popstate事件监听的，需要自定义事件
  const onPopState = (e: PopStateEvent) => {
    history.value = e;
  };
  const { removeEvent: removePopstateEvent } = useEventListener({ el: window, eventName: 'popstate', listener: onPopState });

  const onPushState = () => {
    history.value = window.history;
    console.log('historyState', historyState.value);
  };

  const onReplaceState = () => {
    history.value = window.history;
  };

  const { removeEvent: removePushStateEvent } = useEventListener({ el: window, eventName: 'pushState', listener: onPushState });
  const { removeEvent: removeReplaceStateEvent } = useEventListener({ el: window, eventName: 'replaceState', listener: onReplaceState });

  onBeforeUnmount(() => {
    removePopstateEvent && removePopstateEvent();
    removePushStateEvent && removePushStateEvent();
    removeReplaceStateEvent && removeReplaceStateEvent();
  });

  return { history, historyState, canBack, canForward };
};

export default useHistory;
